/***************************************************************************************
* Copyright (c) 2014-2022 Zihao Yu, Nanjing University
*
* NEMU is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*          http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
*
* See the Mulan PSL v2 for more details.
***************************************************************************************/

#include <isa.h>
#include <cpu/cpu.h>
#include <readline/readline.h>
#include <readline/history.h>
#include "sdb.h"

#define STRtoNUM(num_ptr) atoi(num_ptr)

static int is_batch_mode = false;

void init_regex();
void init_wp_pool();
word_t paddr_read(paddr_t,int);
void isa_reg_display();
void watchpoint_display();

/* We use the `readline' library to provide more flexibility to read from stdin. */
static char* rl_gets() {//获取输入
  static char *line_read = NULL;

  if (line_read) {
    free(line_read);
    line_read = NULL;
  }

  line_read = readline("(nemu) ");

  if (line_read && *line_read) {
    add_history(line_read);
  }
  return line_read;
}

static int cmd_c(char *args) { //continue命令
  cpu_exec(-1);
  return 0;
}


static int cmd_q(char *args) {  //q 退出命令
  return -1;
}

static int cmd_help(char *args);

static int cmd_si(char *args){
  if(args !=NULL){
    char *arg=strtok(NULL," ");//现在arg指向第一个参数
    int n=STRtoNUM(arg);
    cpu_exec(n);
  }else{
    cpu_exec(1);
  }
  return 0;
}

static int cmd_info(char * args){
  //char *ctype=strtok(NULL," "); 这里args已经是第一个参数的位置了
  if(args==NULL){printf("comments needs to be provided");}
  else if (strcmp(args,"r")==0){
    printf("%s",args);
    isa_reg_display();
  }else if(strcmp(args,"w")==0){
    //循环打印监视点
    watchpoint_display();
  }else printf("wrong command!");
  return 0;
}


static int cmd_x(char *args){
  //char *p_num=strtok(NULL," ");
  if(args==NULL) {printf("wrong command!");return 0;}
  int n;//=STRtoNUM(args);
  /*char *p_expr=strtok(NULL," ");
  //求出表达式的值，应该是一个用于标识内存地址的16进制整数
  bool *success;
  word_t exp=expr(p_expr,success);*/
  word_t start_addr;
  sscanf(args,"%d%x",&n,&start_addr);
  for(int i=0;i<n;i++){
    printf("%x\n",paddr_read(start_addr,4));//16进制输出
    start_addr+=4;
  }
  return 0;
}

static int cmd_p(char * args){
  bool success=true;
  word_t exp=expr(args,&success);
  if(success){
    printf("%d\n",exp);
  }
  else printf("invlid expression\n");
  return 0;
}
/*
static int cmd_w(char * args){
  bool *legal;
  word_t result=expr(args,legal);
  if(legal) return 0;
  else return -1;
}

static int cmd_d(char *args){
  //int n=GETNUM(args);
  //删除标号为n的监视点，从监视点池wp_pool中
  return 0;
}*/


static struct {
  const char *name;
  const char *description;
  int (*handler) (char *);
} cmd_table [] = {
  { "help", "Display information about all supported commands", cmd_help },
  { "c", "Continue the execution of the program", cmd_c },
  { "q", "Exit NEMU", cmd_q },

  /* TODO: Add more commands */
  { "si","execute", cmd_si },
  { "info","print regs and watch point", cmd_info},
  
  { "x","out put value in memory",cmd_x},
  { "p","get the value of expressions",cmd_p},/*
  { "w","",cmd_w},
  { "d","",cmd_d},*/

};

#define NR_CMD ARRLEN(cmd_table) //cmd_table的数组长度

static int cmd_help(char *args) {
  /* extract the first argument */
  char *arg = strtok(NULL, " ");
  int i;

  if (arg == NULL) {
    /* no argument given */
    for (i = 0; i < NR_CMD; i ++) {
      printf("%s - %s\n", cmd_table[i].name, cmd_table[i].description);
    }
  }
  else {
    for (i = 0; i < NR_CMD; i ++) {
      if (strcmp(arg, cmd_table[i].name) == 0) {
        printf("%s - %s\n", cmd_table[i].name, cmd_table[i].description);
        return 0;
      }
    }
    printf("Unknown command '%s'\n", arg);
  }
  return 0;
}

void sdb_set_batch_mode() {
  is_batch_mode = true;
}

void sdb_mainloop() {
  if (is_batch_mode) {
    cmd_c(NULL);
    return;
  }

  for (char *str; (str = rl_gets()) != NULL; ) {
    char *str_end = str + strlen(str);  //readline的结束位置

    /* extract the first token as the command */
    char *cmd = strtok(str, " ");//第一次调用分隔用户输入，cmd指向用户输入开头，也就是命令的名字
    if (cmd == NULL) { continue; }

    /* treat the remaining string as the arguments,
     * which may need further parsing
     */
    char *args = cmd + strlen(cmd) + 1; //指向下一个token（如果有参数）
    if (args >= str_end) { //判断这条命令没有参数
      args = NULL;
    }//实际上，这里的args并不会影响后续命令处理中的，这里只是赋值去看了一下，
    //并且会用于之后的命令处理，比如si命令如果没有参数那就是默认为1
    //而且大眼睛，那里的变量是arg

#ifdef CONFIG_DEVICE
    extern void sdl_clear_event_queue();
    sdl_clear_event_queue();
#endif

    int i;
    for (i = 0; i < NR_CMD; i ++) { //逐个比对确定是哪个命令
      if (strcmp(cmd, cmd_table[i].name) == 0) {
        if (cmd_table[i].handler(args) < 0) { return; } //这里就已经在调用相应的函数了，<0说明处理过程出现了错误，程序提前结束
                         //指向那个命令实现函数的指针        //或者说是输入的命令quit，直接返回了-1退出程序
        break;//找到了，跳出循环
      }
    }

    if (i == NR_CMD) { printf("Unknown command '%s'\n", cmd); }//比对了所有的都没有找到对应的命令
  }
}

void init_sdb() {
  /* Compile the regular expressions. */
  init_regex();

  /* Initialize the watchpoint pool. */
  init_wp_pool();
}
